package com.yt.user.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.user.models.dto.LoginDTO;
import com.yt.user.models.dto.RegisterDTO;
import com.yt.user.models.dto.ResetPasswordDTO;
import com.yt.user.models.dto.UserInfoDTO;
import com.yt.user.models.entity.User;
import com.yt.user.models.vo.LoginVO;
import com.yt.user.server.mapper.UserMapper;
import com.yt.user.server.service.UserService;
import com.yt.common.utils.Md5Utils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * 用户服务实现类
 * 使用MyBatis Plus进行查询
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Override
    public boolean register(RegisterDTO registerDTO) {
        // 检查账号是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", registerDTO.getAccount());
        queryWrapper.eq("is_delete", 0);
        User existingUser = this.getOne(queryWrapper);
        if (existingUser != null) {
            throw new RuntimeException("账号已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setAccount(registerDTO.getAccount());
        user.setName(registerDTO.getName());
        user.setIdCard(registerDTO.getIdCard());
        
        // 生成盐值并加密密码
        String salt = UUID.randomUUID().toString().replace("-", "");
        String encryptedPassword = Md5Utils.MD5Encode(registerDTO.getPassword(), salt);
        
        user.setPassword(encryptedPassword);
        user.setSalt(salt);
        user.setIsDelete(0);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        
        // 插入数据库
        return this.save(user);
    }
    
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        // 根据账号查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", loginDTO.getAccount());
        queryWrapper.eq("is_delete", 0);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException("账号不存在");
        }
        
        // 验证密码
        String encryptedPassword = Md5Utils.MD5Encode(loginDTO.getPassword(), user.getSalt());
        if (!encryptedPassword.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 生成登录令牌（简单实现，实际项目中可使用JWT）
        String token = UUID.randomUUID().toString().replace("-", "");
        
        // 构造返回结果
        LoginVO loginVO = new LoginVO();
        loginVO.setId(user.getId());
        loginVO.setAccount(user.getAccount());
        loginVO.setName(user.getName());
        loginVO.setToken(token);
        
        return loginVO;
    }
    
    @Override
    public boolean resetPassword(ResetPasswordDTO resetPasswordDTO) {
        // 根据账号和身份证号查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", resetPasswordDTO.getAccount());
        queryWrapper.eq("id_card", resetPasswordDTO.getIdCard());
        queryWrapper.eq("is_delete", 0);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new RuntimeException("用户信息不匹配");
        }
        
        // 生成新的盐值并加密新密码
        String newSalt = UUID.randomUUID().toString().replace("-", "");
        String encryptedNewPassword = Md5Utils.MD5Encode(resetPasswordDTO.getNewPassword(), newSalt);
        
        // 更新用户密码和盐值
        user.setPassword(encryptedNewPassword);
        user.setSalt(newSalt);
        user.setUpdateTime(new Date());
        
        return this.updateById(user);
    }
    
    @Override
    public User getUserByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        queryWrapper.eq("is_delete", 0);
        return this.getOne(queryWrapper);
    }
    
    @Override
    public boolean saveUserInfo(UserInfoDTO userInfoDTO) {
        // 根据insurantId获取用户信息
        User user = this.getById(userInfoDTO.getInsurantId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 合并更新用户信息
        // 这里我们假设只更新姓名和身份证号字段
        if (userInfoDTO.getBeneficiaryName() != null) {
            user.setName(userInfoDTO.getBeneficiaryName());
        }
        
        if (userInfoDTO.getBeneficiaryIdcard() != null) {
            user.setIdCard(userInfoDTO.getBeneficiaryIdcard());
        }
        
        user.setUpdateTime(new Date());
        
        // 更新数据库
        return this.updateById(user);
    }
}